package com.ddyx.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.codec.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddyx.common.util.ImageFileUtil;
import com.ddyx.service.ICustomerService;

@Controller
@RequestMapping("/headImage")
public class HeadImageController {

	private static String tempPicturePath = "C:\\pictures" + File.separator + "test" + File.separator;
	
	@Resource
	ICustomerService customerService;
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Map<String, Object> saveHeadImage(String base64Str,int customerId) {
		Map<String, Object> map = new HashMap<>();
		byte[] data = Base64.decode(base64Str);
		String uuid = UUID.randomUUID().toString();
		String pictureName = uuid+".jpg";
		String imagePath = tempPicturePath+pictureName;
		ImageFileUtil.byte2image(data, imagePath);
		if(customerService.saveHeadImage(customerId, pictureName)) {
			map.put("status", true);
		}else {
			map.put("status", false);
		}
		return map;
	}
	
	@RequestMapping(value="/get")
	public void getHeadImage(String pictureName,HttpServletResponse response) throws IOException {
		InputStream pictureInputStream = null;
        OutputStream pictureOutputStream = null;
        try {
			if(pictureName == null || "".equals(pictureName)) {
				pictureName = "defaultPicture.jpg";
			}
			String imagePath = tempPicturePath+pictureName;
			if (new File(imagePath).exists()) {
			    pictureInputStream = new FileInputStream(imagePath);
			    pictureOutputStream = response.getOutputStream();
			    byte[] data = new byte[1024];
			    while(pictureInputStream.read(data) != -1) {
			    	pictureOutputStream.write(data);
			    }
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
        	if(pictureInputStream != null){
        		pictureInputStream.close();
        	}
        	if(pictureOutputStream != null){
        		pictureOutputStream.close();
        	}
        }
	}
}
